package com.gcloud.mesh.monitor.cloud;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.jeecg.common.exception.MyBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.teaopenapi.models.Config;
import com.gcloud.mesh.asset.dao.CloudResourceConfigDao;
import com.gcloud.mesh.asset.entity.CloudResourceConfigEntity;
import com.gcloud.mesh.dcs.dao.AppInstanceDao;
import com.gcloud.mesh.dcs.entity.AppInstanceEntity;
import com.gcloud.mesh.header.param.AliMigrationParam;
import com.gcloud.mesh.header.vo.dcs.DescribeMetricVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class AliMonitor extends VMCloudMonitor implements ICloudBaseMonitor{
	
    @Autowired
    private AppInstanceDao instanceDao;
    @Autowired
    private CloudResourceConfigDao cloudResourceConfigDao;

	
    public List<DescribeMetricVO> queryDescribeMetricLastList(String cloudResourceId) {
    	// List<AppEntity> appList = aliQueryInstance.queryServerList(cloudResourceId);
    	List<AppInstanceEntity> instances = instanceDao.findByCloudResourceId(cloudResourceId);
		CloudResourceConfigEntity cloudResource = cloudResourceConfigDao.findOneByProperty("cloud_resource_id", cloudResourceId);
        if(cloudResource==null) return Lists.newArrayList();

        AliMigrationParam aliMigrationParam = JSONObject.toJavaObject(JSONObject.parseObject(cloudResource.getConfig()), AliMigrationParam.class);
        Map<String,String> appMap = Maps.newHashMap();
        if(instances!=null && !instances.isEmpty()){
            List<JSONObject> dimensions = instances.stream().map(a -> {
                JSONObject json = new JSONObject();
                json.put("instanceId", a.getInstanceId());
                appMap.put(a.getInstanceId(),a.getName());
                return json;
            }).collect(Collectors.toList());
            if(aliMigrationParam!=null){
                String accessKeyId = aliMigrationParam.getAccessKeyId();
                String accessKeySecret = aliMigrationParam.getAccessSecret();
                Config config = new Config()
                        // 您的AccessKey ID
                        .setAccessKeyId(accessKeyId)
                        // 您的AccessKey Secret
                        .setAccessKeySecret(accessKeySecret);
                // 访问的域名
                config.endpoint = "metrics."+aliMigrationParam.getRegionId()+".aliyuncs.com";
                try {
                    com.aliyun.cms20190101.Client client =  new com.aliyun.cms20190101.Client(config);
                    com.aliyun.cms20190101.models.DescribeMetricLastRequest describeMetricLastRequest = new com.aliyun.cms20190101.models.DescribeMetricLastRequest()
                            .setMetricName("cpu_total")
                            .setDimensions(JSONObject.toJSONString(dimensions))
                            .setNamespace("acs_ecs_dashboard");
                    // CPU
                    String datapoints = client.describeMetricLast(describeMetricLastRequest).getBody().getDatapoints();
                    JSONArray jsonArray = JSONArray.parseArray(datapoints);
                    List<DescribeMetricVO> resultList = Lists.newArrayList();
                    for (Object o : jsonArray) {
                        if(o instanceof JSONObject){
                            JSONObject json = (JSONObject)o;
                            String instanceId = json.getString("instanceId");
                            String cpuVal = json.getString("Average");
                            resultList.add(new DescribeMetricVO().setInstanceId(instanceId).setCupVal(cpuVal).setInstanceName(appMap.get(instanceId)));
                        }
                    }

                    //内存
                    describeMetricLastRequest.setMetricName("memory_usedutilization");
                    datapoints = client.describeMetricLast(describeMetricLastRequest).getBody().getDatapoints();
                    jsonArray = JSONArray.parseArray(datapoints);
                    Map<String,String> memMap = Maps.newHashMap();
                    for (Object o : jsonArray) {
                        if(o instanceof JSONObject){
                            JSONObject json = (JSONObject)o;
                            String instanceId = json.getString("instanceId");
                            String memVal = json.getString("Average");
                            memMap.put(instanceId,memVal);
                        }
                    }
                    return resultList.stream().map(d->{
                        return d.setMemVal(memMap.get(d.getInstanceId()));
                    }).collect(Collectors.toList());

                } catch (Exception e) {
                    log.error("查询阿里云虚拟机使用情况错误",e);
                    throw new MyBusinessException("查询阿里云虚拟机使用情况错误");
                }

            }

        }

        return Lists.newArrayList();
    }
    
}
